﻿function Menu_Index() {

    var menuModel = Ext.define("menuModel", {
        extend: 'Ext.data.Model',
        fields: [{ name: 'id', type: 'int' },
                { name: 'actionName', type: 'string' },
                { name: 'controllerName', type: 'string' },
                { name: 'actionDescription', type: 'string' },
                { name: 'controllerDescription', type: 'string' },
                { name: 'prevIcon', type: 'string' },
                { name: 'menuName', type: 'string' },
                { name: 'parentId', type: 'int' },
                { name: 'leaf', type: 'bool' },
                { name: 'url', type: 'string' },
                { name: 'createTime', type: 'string' },
                { name: 'nodeLevel', type: 'int' }
            ]
    });

    var store = Ext.create('Ext.data.TreeStore', {
        model: 'menuModel',
        proxy: {
            type: 'ajax',
            url: 'Admin/Menu/GetMenuGrid',
            actionMethods: { read: 'POST' }, //将提交方式改为post
            waitMsg: '数据加载中...',
            reader: {
                type: "json"
            }
        },

        nodeParam: "id",
        root: {
            menuName: "所有菜单",
            actionName: "",
            controllerName: "",
            id: -1,
            parentId: -1000,
            leaf: false,
            nodeLevel: 0,
            expanded: true
        },
        folderSort: true
    });

    var FormReader = Ext.create("Ext.data.JsonReader", {
        model: "menuModel"
    });
    // 工具栏
    var tbar = Ext.create("Ext.toolbar.Toolbar", {
        height: 30,
        id: "tbar",
        items: [{
            text: '添加项',
            cls: "x-button-center",
            icon: "/Content/icons/add.png",
            disabled: true,
            handler: function () {
                //Get the model data of menuModel
                var model = gridTree.getSelectionModel().selected.items[0].data;
                showEditFormWinFn(FormReader, "添加菜单权限", model.id, model.id, model.nodeLevel);
            }
        }, "-", {
            text: '删除项',
            cls: "x-button-center",
            icon: "/Content/icons/delete.png",
            disabled: true,
            handler: function () {
                JsHelper.DelConfirm(function (btn) {
                    if (btn == 'yes') {
                        var model = gridTree.getSelectionModel().selected.items[0].data;
                        var id = model.id;
                        Ext.Ajax.request({
                            url: 'Admin/Menu/DeleteMenu',
                            params: {
                                'id': id
                            },
                            success: function (response, opts) {
                                var result = Ext.JSON.decode(response.responseText);
                                if (result.success == false) {
                                    JsHelper.ShowError(result.msg);
                                }
                                else {
                                    /**这是树刷新的一个bug   解决办法如下**/
                                    var delNode;
                                    while (delNode = store.getRootNode().childNodes[0]) {
                                        store.getRootNode().removeChild(delNode);
                                    }
                                    store.load();
                                    /**以上是树刷新的一个bug**/
                                }
                            }
                        });
                    }
                });
            }
        }, '-', {
            text: "双击修改项",
            cls: "x-button-center",
            icon: "/Content/icons/pencil.png",
            disabled: true
        }, "->", {
            text: "刷新",
            cls: "x-button-center",
            icon: "Content/icons/arrow_refresh.png"
        }]
    });

    var showEditFormWinFn = function (formReader, title, id, parentId, level) {//这里的parentId是获取被更新的项的父Id，添加的项的父Id就是参数id
        var updateEdit = title == "修改菜单权限";
        parentId = (updateEdit) ? parentId : id;
        var disabledColumn = parentId == 'undefined' || parentId == null || parentId <= 0;

        // 定义表单验证成功后的提交参数及返回处理
        var formSubmitArgs = {
            url: updateEdit ? "Admin/Menu/EditMenu" : "Admin/Menu/AddMenu",
            params: {
                "id": updateEdit ? id : "",
                "parentId": (updateEdit) ? "" : id,
                'nodeLevel': (updateEdit) ? level : level + 1,
                "leaf": (updateEdit) ? level >= 2 : level < 1
            },
            success: function (formObj, action) {
                win.destroy(); // 关闭窗口
                /**这是树刷新的一个bug   解决办法如下**/
                var delNode;
                while (delNode = store.getRootNode().childNodes[0]) {
                    store.getRootNode().removeChild(delNode);
                }
                store.load();
                /**以上是树刷新的一个bug**/
            },
            failure: function (formObj, action) {
                switch (action.failureType) {
                    case Ext.form.action.Action.CLIENT_INVALID:
                        Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
                        //JsHelper.ShowError(action.result.msg);
                        break;
                    case Ext.form.action.Action.CONNECT_FAILURE:
                        //Ext.Msg.alert('Failure', 'Ajax communication failed');
                        JsHelper.ShowError(action.result.msg);
                        break;
                    case Ext.form.action.Action.SERVER_INVALID:
                        JsHelper.ShowError(action.result.msg);
                }
            }
        };
        // 定义获得表单初始加载数据的请求参数
        var formLoadArgs = (updateEdit) ? {
            url: 'Admin/Menu/GetMenuById',
            params: {
                'id': id
            },
            actionMethods: { read: 'POST' }, //将提交方式改为post
            waitMsg: '数据加载中...'
        } : null;

        // 定义表单第一列的组件对象集合 默认xtype为textfield
        var firstColumn = [{
            fieldLabel: '<span style="color: red;" >*</span>菜单名称',
            allowBlank: false,
            name: 'menuName'
        }, {
            fieldLabel: '图标',
            name: 'prevIcon'
        }, {
            fieldLabel: '动作名称',
            name: 'actionName',
            disabled: disabledColumn,
            disabledCls: "text-disabled"
        }, {
            fieldLabel: '控制器名称',
            name: 'controllerName',
            disabled: disabledColumn,
            disabledCls: "text-disabled"
        }, {
            fieldLabel: '动作描述',
            name: 'actionDescription',
            disabled: disabledColumn,
            disabledCls: "text-disabled",
            colspan: 2,
            width: 640
        }, {
            fieldLabel: '控制器描述',
            name: 'controllerDescription',
            colspan: 2,
            width: 640,
            disabled: disabledColumn,
            disabledCls: "text-disabled"
        }, {
            fieldLabel: 'Url',
            name: 'url',
            disabled: disabledColumn,
            disabledCls: "text-disabled"
        }, {
            fieldLabel: '是否启用',
            allowBlank: false,
            name: 'enabled',
            xtype: "checkboxfield"
        }];

        var form = Ext.create("Ext.form.Panel", {
            border: false,
            waitMsgTarget: true,
            bodyStyle: 'padding:10px;',
            reader: formReader,
            defaults: {
                labelWidth: 90,
                labelAlign: 'right',
                width: 320
            },
            defaultType: 'textfield',
            layout: {
                columns: 2,
                type: 'table',
                tableAttrs: {
                    style: {
                        width: '100%'
                    }
                }
            },
            buttonAlign: 'center',
            buttons: [{
                text: '提交',
                cls: "x-button-center",
                icon: "Content/icons/accept.png",
                handler: function () {
                    if (form.getForm().isValid()) {
                        form.getForm().submit(formSubmitArgs); // formSubmitArgs
                        // 引用之前定义的请求参数变量
                    }
                }
            }, {
                text: '取消',
                cls: "x-button-center",
                icon: "Content/icons/cancel_new.png",
                handler: function () {
                    win.destroy();
                }
            }],
            items: firstColumn
        });

        //定义显示窗口
        var win = Ext.create("Ext.window.Window", {
            title: title,
            iconCls: 'application_form',
            resizable: false,
            autoHeight: true,
            modal: true,
            bodyStyle: 'background:#ffffff;padding-bottom:8px',
            items: [form]
        });

        win.show();
        // 判断是否为表单加载初始数据
        if (formLoadArgs) {
            form.load(formLoadArgs); // formLoadArgs 引用之前定义表单数据加载的请求参数变量
        };
    };

    var gridTree = Ext.create("Ext.tree.Panel", {
        //rootVisible: false,
        store: store,
        multiSelect: true,
        singleExpand: false,
        layout: "fit",
        tbar: tbar,
        lines: false,
        stripeRows: true,
        useArrows: true,
        columns: [{
            xtype: "treecolumn", //这个列示树形的
            text: "菜单名称",
            dataIndex: "menuName",
            flex: 3.5
        }, {
            text: "动作名称",
            dataIndex: "actionName",
            flex: 2.5
        }, {
            text: "控制器名称",
            dataIndex: "controllerName",
            flex: 2.5
        }, {
            text: "动作描述",
            dataIndex: "actionDescription",
            flex: 4
        }, {
            text: "控制器描述",
            dataIndex: "controllerDescription",
            flex: 4
        }, {
            text: "图标",
            dataIndex: "prevIcon",
            flex: 2
        }, {
            text: "链接地址",
            dataIndex: "url",
            flex: 2
        }, {
            text: "是否叶子",
            dataIndex: "leaf",
            flex: 1.5
        }, {
            //xtype: 'datecolumn',
            renderer: Ext.util.Format.dateRenderer('Y年m月d日 H时i分'),
            text: "创建时间",
            dataIndex: "createTime",
            flex: 3
        }],
        listeners: {
            "itemclick": function (cmp, record, item, index, e, eOpts) {
                var id = record.data.id;
                var level = record.data.nodeLevel;
                var leaf = record.data.leaf;
                var topBar = Ext.getCmp("tbar");
                topBar.items.getAt(0).setDisabled(level >= 2); //添加
                topBar.items.getAt(2).setDisabled(!leaf); //删除
            },
            "itemdblclick": function (cmp, record, item, index, e, eOpts) {
                var id = record.data.id;
                var parentId = record.data.parentId;
                if (id <= 0) return false;
                var level = record.data.nodeLevel;
                showEditFormWinFn(FormReader, "修改菜单权限", id, parentId, level);
                return true;
            }
        }
    });

    JsHelper.ExtTabDoLayout(gridTree);
}

Menu_Index();